<template>
  <div class="form-item-full">
    <div
      class="item-input"
      v-loading="showProgress"
      element-loading-text="拼命上传中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0)"
    >
      <ul class="upload-block">
        <li class="upload-item" v-for="(item, index) of list" :key="index">
          <img class="upload-img" src="../assets/images/picImg.png" />
          <div class="upload-text" :title="item.acsName" @click="openFile(item)">{{ item.acsName }}</div>
          <span v-if="isEdit" class="upload-close" @click="deleteFile(item.acsUrl)">
            <i class="el-icon-close" style=" transform:scale(0.7);"></i>
          </span>
        </li>
      </ul>
      <div v-if="isEdit">
        <el-progress :percentage="percentageNum" v-if="showProgress"></el-progress>
        <div class="upload-row">
          <el-upload
            action
            :show-file-list="false"
            :limit="5"
            :on-exceed="handleExceed"
            :file-list="list"
            :before-upload="beforeAvatarUpload"
          >
            <el-tag type="primary" size="medium">添加附件</el-tag>
          </el-upload>
        </div>
        <div slot="tip" class="el-upload__tip">
          可上传图片 ( 最大2M ) 、视频 ( 最大100M ) 、音频 ( 最大10M )
          、文档类文件 ( 最大5M ) ；最多可上传5个文件
        </div>
        <div class="errorInfo" v-if="uploadErr !== ''">{{ uploadErr }}</div>
      </div>
    </div>
  </div>
</template>
<script>
import Api from "@/constants/Api";

export default {
  props: {
    fileList: {
      type: Array
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  watch: {
    fileList(val) {
      this.list = val;
    }
  },
  data() {
    return {
      url: this.$global.baseUrl,
      uploadErr: "",
      showProgress: false,
      dialogTableVisible: false,
      imgDetail: "",
      percentageNum: 0,
      list: this.fileList
    };
  },

  methods: {
    openFile(item) {
      let url = "";
      url = this.$global.baseUrl + item.acsUrl;
      const downloadFileA = document.createElement("a");
      document.body.append(downloadFileA);
      downloadFileA.href = url;
      downloadFileA.download = url;
      downloadFileA.target = "_blank";
      downloadFileA.rel = "noopener noreferrer";
      downloadFileA.click();
      document.body.removeChild(downloadFileA);
    },
    handleExceed(files, list) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + list.length} 个文件`
      );
    },
    beforeAvatarUpload(file) {
      const vm = this;
      const fileItem = file.name.split(".");
      let fileType = fileItem[fileItem.length - 1].toLowerCase();
      const isImg = vm.$global.imgType.includes(fileType);
      const isAudio = vm.$global.audioType.includes(fileType);
      const isVideo = vm.$global.videoType.includes(fileType);
      const isDocs = vm.$global.docsType.includes(fileType);
      let bucketName = "";
      let acsType = "";
      vm.uploadErr = "";
      vm.imgLoading = true;
      if (!(isImg || isAudio || isVideo || isDocs)) {
        vm.uploadErr = "请上传正确的文件格式";
        return false;
      }

      if (isImg) {
        acsType = "P";
        bucketName = "img";
      }
      if (isAudio) {
        acsType = "VC";
        bucketName = "audio";
      }
      if (isVideo) {
        acsType = "VD";
        bucketName = "video";
      }
      if (isDocs) {
        acsType = "D";
        bucketName = "file";
      }
      // 传文件
      if (isImg || isAudio || isVideo || isDocs) {
        let fd = new FormData();
        fd.append("file", file);
        let fileSize = fd.get("file").size / 1024 / 1024;
        if (isImg && fileSize > 2) {
          vm.uploadErr = "图片大小不能超过2M";
          return false;
        }
        if (isAudio && fileSize > 10) {
          vm.uploadErr = "音频大小不能超过10M";
          return false;
        }
        if (isVideo && fileSize > 100) {
          vm.uploadErr = "视频大小不能超过100M";
          return false;
        }
        if (isDocs && fileSize > 5) {
          vm.uploadErr = "文档大小不能超过5M";
          return false;
        }
        vm.showProgress = true;
        vm.percentageNum = 0;
        let url = Api.fileUpload.replace("{bucketName}", bucketName);
        vm.$axios({
          method: "post",
          url: url,
          data: fd,
          headers: { "Content-Type": "multipart/form-data" },
          timeout: 1000 * 60 * 60,
          onUploadProgress: progressEvent => {
            if (progressEvent.lengthComputable) {
              let perc = Math.round(
                (progressEvent.loaded / progressEvent.total) * 100
              );
              vm.percentageNum = perc > 95 ? 95 : perc;
            }
          }
        })
          .then(res => {
            if (res.code === 20002) {
              vm.percentageNum = 100;
              vm.showProgress = false;
              let obj = {
                acsName: res.data.originalFileName,
                acsType: acsType,
                acsUrl: res.data.filePath
              };
              vm.list.push(obj);
            } else {
              vm.percentageNum = 100;
              vm.showProgress = false;
              vm.uploadErr = res.msg;
            }
          })
          .catch(err => {
            vm.percentageNum = 0;
            vm.showProgress = false;
            vm.uploadErr = err.message;
          });
      } else {
        return false;
      }
    },
    async deleteFile(path) {
      let vm = this;
      vm.$axios({
        method: "delete",
        url: Api.fileDelete,
        params: {
          path: path
        }
      })
        .then(res => {
          if (res.code === 20004) {
            vm.list.splice(
              vm.list.findIndex(item => item.acsUrl === path),
              1
            );
          } else {
            vm.$message.error(res.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>
<style type="text/scss" lang="scss" scoped>
@import "~/common.scss";

.form-item-full {
  border-radius: 0px 0px 8px 8px;
  .item-label {
    float: left;
    width: 30%;
    text-align: right;
    padding-right: 10px;
    @include line-height(60px);
  }
  .item-code-label {
    float: left;
    width: 10%;
    text-align: center;
    padding-right: 10px;
    @include line-height(60px);
  }
  .item-input {
    position: relative;
    float: left;
    width: 100%;
    text-align: left;
    p {
      color: $red;
      line-height: 1.5;
    }
  }
}

.upload-block {
  .upload-item {
    position: relative;
    width: 400px;
    @include line-height(30px);
    background: #fff;
    border-radius: 4px;
    transition: transform 0.1s;
    -moz-transition: -moz-transform 0.1s;
    -webkit-transition: -webkit-transform 0.1s;
    -o-transition: -o-transform 0.1s;
    &:hover {
      background: #f3f4f8;
      color: #4977fc;
      transform: translateX(-2px);
      -moz-transform: translateX(-2px);
      -webkit-transform: translateX(-2px);
      -o-transform: translateX(-2px);
    }
    .upload-img {
      width: 18px;
      height: 18px;
      transform: translateY(-2px);
      vertical-align: middle;
      margin: 0 5px 0 0px;
    }
    .upload-text {
      display: inline-block;
      @include line-height(18px);
      @include div-nowrap();
      transform: translateY(3px);
      &:hover {
        cursor: pointer;
      }
    }
    .upload-close {
      position: absolute;
      top: 0;
      right: 10px;
    }
  }
}

.upload-row {
  padding: 0;
  margin: 0;
  height: 40px;
  .upload-btn {
    display: inline-block;
    margin: 0 auto;
    border: 1px solid $red;
    border-radius: 5px;
    color: $red;
    cursor: pointer;
    font-size: $font12;
    padding: 1px 8px;
    text-align: center;
    .upload-img {
      display: inline-block;
      width: 14px;
      height: 14px;
      vertical-align: middle;
      margin-right: 3px;
    }
  }
}

.errorInfo {
  padding-top: 5px;
  color: $red;
}

/deep/ .img-show {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  margin-top: 0 !important;
  width: auto;
  text-align: center;
  .el-dialog__body {
    padding: 0px;
  }
  .el-dialog__header {
    padding: 0px;
  }
  img {
    max-width: 100%;
    height: auto;
  }
}

.preStyle {
  color: $red;
}
</style>
